import axios from 'axios'
import {useUserStore} from '@/stores/user' //  Pinia
import {refresh} from "@/api/index.js";
import {ElMessage} from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'


const baseURL = import.meta.env.VITE_API_URL
const request = axios.create({
    baseURL: baseURL,
    timeout: 5000
})
// 请求拦截器
request.interceptors.request.use(
    config => {
        NProgress.start()
        const token = sessionStorage.getItem('access') || localStorage.getItem('access')
        if (token) {
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    error => {
        NProgress.done()
        return Promise.reject(error)
    }
)

// 响应拦截器
request.interceptors.response.use(
    response => {
        NProgress.done()
        return response
    },
    async error => {
        const originalRequest = error.config
        // 如果是401错误，且尚未重试过（防止无限循环）
        if (error.response && error.response.status === 401 && !originalRequest.retry) {
            originalRequest.retry = true
            const refreshToken = localStorage.getItem('refresh') || sessionStorage.getItem('refresh')
            if (refreshToken) {
                try {
                    // 必须调用裸axios刷新refresh，否则陷入request循环
                    const res = await axios.post(`${baseURL}users/refresh/`, {refresh: refreshToken})
                    const newAccess = res.data.access
                    const newRefresh = res.data.refresh
                    // 更新本地access refresh
                    localStorage.setItem('access', newAccess)
                    localStorage.setItem('refresh', newRefresh)
                    // 更新请求头重新发起请求
                    originalRequest.headers.Authorization = `Bearer ${newAccess}`
                    // 重新发起原始请求
                    return request(originalRequest)
                } catch (refreshError) {
                    NProgress.done()
                    ElMessage.warning("登录失效")
                    const userStore = useUserStore()
                    userStore.logout()
                    return Promise.reject(refreshError)
                }
            } else {
                // ✅ 添加：没有refreshToken时的处理
                NProgress.done()
                ElMessage.warning("登录失效")
                const userStore = useUserStore()
                userStore.logout()
            }
        }
        NProgress.done()
        return Promise.reject(error)
    }
)

export default request
